package xyz.xtt.equity.service.impl;

import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import xyz.xtt.common.starter.cache.CacheManager;
import xyz.xtt.equity.constants.AssetCache;
import xyz.xtt.equity.entity.TblRegion;
import xyz.xtt.equity.mapper.TblRegionMapper;
import xyz.xtt.equity.service.ITblRegionService;
import xyz.xtt.equity.vo.PhoneRegionVo;

/**
 * 行政区划服务
 *
 * @author dale
 * @since 2025/1/2
 **/
@Service
public class TblRegionServiceImpl extends ServiceImpl<TblRegionMapper, TblRegion> implements ITblRegionService {
	@Autowired
	private CacheManager cacheManager;

	@Override
	public List<PhoneRegionVo> getRegionList(String parentId) {
		Long pid = StringUtils.isNotBlank(parentId) ? Long.valueOf(parentId) : 0L;
		return cacheManager.cacheList(() -> this.getRegionListFromDB(pid), AssetCache.LUCK_PHONE_REGION_LIST, parentId);
	}

	/**
	 * 从数据库获取归属地列表
	 * 
	 * @param pid
	 * @return
	 */
	private List<PhoneRegionVo> getRegionListFromDB(long pid) {
		QueryWrapper<TblRegion> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("parent_id", pid);
		queryWrapper.eq("is_del", 0);
		queryWrapper.orderByAsc("region_pinyin");
		List<TblRegion> list = baseMapper.selectList(queryWrapper);
		if (CollectionUtils.isEmpty(list)) {
			return Collections.emptyList();
		}
		return list.stream().map(region -> new PhoneRegionVo(region.getId().toString(), region.getRegionName(), region.getRegionLevel())).toList();
	}
}
